package com.hhkj.api.sale.service.biz.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageInfo;
import com.hhkj.admin.sale.common.cont.SaleConst;
import com.hhkj.admin.sale.common.utils.SaleLevelUtils;
import com.hhkj.admin.sale.common.utils.SaleNumUtils;
import com.hhkj.admin.sale.common.utils.SalePasswordUtils;
import com.hhkj.admin.sale.domain.Sale;
import com.hhkj.admin.sale.model.dopo.SalePo;
import com.hhkj.admin.sale.service.base.SaleAccountService;
import com.hhkj.admin.sale.service.base.SaleService;
import com.hhkj.api.common.common.component.checker.CaptchaChecker;
import com.hhkj.api.common.common.cont.SaleCaptchaTypeEnum;
import com.hhkj.api.sale.common.component.checker.ApiSaleChecker;
import com.hhkj.api.sale.common.session.holder.ApiSaleSessionHolder;
import com.hhkj.api.sale.model.req.ApiSaleRegisterReq;
import com.hhkj.api.sale.model.req.ApiSaleReq;
import com.hhkj.api.sale.model.req.ApiSaleResetPasswordReq;
import com.hhkj.api.sale.model.req.ApiSaleUpdatePwReq;
import com.hhkj.api.sale.model.res.ApiSaleRes;
import com.hhkj.api.sale.service.biz.ApiSaleBizService;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.paging.PageInfoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * ApiSaleBizServiceImpl
 *
 * @author HHKJ-SERVER-ZJ
 * @since 2023/10/25 14:46
 */
@Service
public class ApiSaleBizServiceImpl implements ApiSaleBizService {

    @Autowired
    private SaleService saleService;
    @Autowired
    private ApiSaleChecker apiSaleChecker;
    @Autowired
    private SaleAccountService saleAccountService;
    @Autowired
    private CaptchaChecker captchaChecker;

    @Override
    public boolean updatePassword(ApiSaleUpdatePwReq req) {
        // 校验密码格式
        this.checkNewPwFormat(req.getPassword());
        // 获取现在登录用户信息
        Long saleId = ApiSaleSessionHolder.getSaleId();
        Sale sale = saleService.getById(saleId);
        captchaChecker.check(SaleCaptchaTypeEnum.UPDATE_PASSWORD.getCode(), req.getMobile(), req.getCaptcha());
        // 查看旧密码是否正确
        if (!SecurityUtils.matchesPassword(req.getOldPassword(), sale.getPassword())) {
            throw new GlobalException("旧密码不正确");
        }
        // 修改密码
        // 3、修改密码
        String password = SalePasswordUtils.encryptPassword(req.getPassword());
        sale.setPassword(password);
        return saleService.updateById(sale);
    }

    /**
     * 校验传入密码格式
     *
     * @param password 密码
     */
    private void checkNewPwFormat(String password) {
        if (!SalePasswordUtils.checkFormat(password)) {
            throw new GlobalException("密码格式不正确，有8-20位字母数字构成");
        }
    }

    @Override
    public boolean resetPassword(ApiSaleResetPasswordReq req) {
        this.checkNewPwFormat(req.getPassword());
        // 1、校验验证码信息
        captchaChecker.check(SaleCaptchaTypeEnum.RESET_PASSWORD.getCode(), req.getMobile(), req.getCaptcha());
        // 2、根据手机号码获取商家信息
        Sale salePo = saleService.getByMobile(req.getMobile());
        if (ObjectUtil.isNull(salePo)) {
            throw new GlobalException("账号不存在，请确认后重试");
        }
        // 3、修改密码
        String password = SalePasswordUtils.encryptPassword(req.getPassword());
        salePo.setPassword(password);
        return saleService.updateById(salePo);
    }

    @Override
    public PageInfo<ApiSaleRes> pagingChildren(ApiSaleReq req) {
        Long saleId = ApiSaleSessionHolder.getSaleId();
        req.setParentId(saleId);
        List<SalePo> salePoList = saleService.listPoByDo(req);
        return PageInfoUtils.toPageInfo(salePoList, ApiSaleRes.class);
    }

    @Override
    public boolean register(ApiSaleRegisterReq req) {
        this.checkNewPwFormat(req.getPassword());
        // 1、校验验证码信息
        captchaChecker.check(SaleCaptchaTypeEnum.REGISTER.getCode(), req.getMobile(), req.getCaptcha());
        // 2、再次校验手机号是否已注册
        apiSaleChecker.checkerMobileRegister(req.getMobile());
        // 3、允许注册 根据邀请码获取上级销售信息
        Sale parentSale = saleService.getByNum(req.getParentNum());
        if (ObjectUtil.isNull(parentSale)) {
            throw new GlobalException("邀请码无效，请重新扫码");
        }
        return this.save(req, parentSale);
    }

    /**
     * 新增
     *
     * @param req        请求信息
     * @param parentSale 上级
     * @return true/false
     */
    private synchronized boolean save(ApiSaleRegisterReq req, Sale parentSale) {
        Sale saleDo = BeanUtil.toBean(req, Sale.class);
        String password = SalePasswordUtils.encryptPassword(req.getPassword());
        saleDo.setPassword(password);
        saleDo.setTypeCode(SaleConst.TypeEnum.SALE.getCode());
        saleDo.setParentId(parentSale.getId());
        // 4、配置编号
        String level = SaleLevelUtils.calculateNextLevel(parentSale.getLevel());
        saleDo.setLevel(level);
        // 5、配置num字段
        Long levelSaleAmount = saleService.countByLevel(level);
        String num = SaleNumUtils.generate(level, levelSaleAmount);
        saleDo.setNum(num);
        // 6、配置所属销售id
        if (SaleConst.TypeEnum.SALE.getCode().equals(parentSale.getTypeCode())) {
            saleDo.setRootId(parentSale.getRootId());
        } else {
            saleDo.setRootId(parentSale.getId());
        }
        Date currentTime = new Date();
        saleDo.setCreateBy(parentSale.getId());
        saleDo.setCreateTime(currentTime);
        saleDo.setRegisterTime(currentTime);
        boolean result = saleService.save(saleDo);
        if (result) {
            // 初始化销售账户
            saleAccountService.initAccount(saleDo.getId());
            saleAccountService.incInvitation(parentSale.getId());
        }
        return result;
    }
}
